package com.drinks.yiniang.utils;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;

import com.drinks.yiniang.App;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.hansen.library.utils.StringUtils;

import java.io.IOException;

/**
 * @author han
 * @date 2019/12/12
 */
public class ZXingUtils {
    public static String scanImage(Uri uri) {
        String qrCode = "";
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(App.getInstance().getContentResolver(), uri);
            bitmap = getSmallerBitmap(bitmap);
            if (bitmap != null) {
                int bitmapWidth = bitmap.getWidth();
                int bitmapHeight = bitmap.getHeight();
                // 1.将bitmap的RGB数据转化成YUV420sp数据
                byte[] bmpYUVBytes = Bmp2YUV.getBitmapYUVBytes(bitmap);
                // 2.塞给zxing进行decode
                qrCode = decodeYUVByZxing(bmpYUVBytes, bitmapWidth, bitmapHeight);

                bitmap.recycle();
                bitmap = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return qrCode;
    }

    private static String decodeYUVByZxing(byte[] bmpYUVBytes, int bmpWidth, int bmpHeight) {
        String zxingResult = "";

        // Both dimensions must be greater than 0
        if (null != bmpYUVBytes && bmpWidth > 0 && bmpHeight > 0) {
            try {
                PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(bmpYUVBytes, bmpWidth,
                        bmpHeight, 0, 0, bmpWidth, bmpHeight, true);
                BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
                Reader reader = new QRCodeReader();
                Result result = reader.decode(binaryBitmap);
                if (null != result) {
                    zxingResult = result.getText();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return zxingResult;
    }

    private static Bitmap getSmallerBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            int size = bitmap.getWidth() * bitmap.getHeight() / 160000;
            if (size <= 1) {
                return bitmap;
            } else {
                Matrix matrix = new Matrix();
                matrix.postScale((float) (1 / Math.sqrt(size)), (float) (1 / Math.sqrt(size)));
                return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            }
        }
        return null;
    }
}
